//
//  DiaryOCViewController.m
//  MoodDiary
//
//  Created by MoodDiary on 2020/12/4.
//

#import "DiaryOCViewController.h"

#import "DiarySectionOCTableViewCell.h"

#import "DiaryOCHeaderView.h"
#import "DiaryOCFooterView.h"
#import "DiaryOCSectionFooterView.h"

#import "MoodDiary-Swift.h"

#import "SVProgressHUD.h"
#import <UMCommon/MobClick.h>
#import "PayViewController.h"
#import <StoreKit/StoreKit.h>
#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>

//沙盒测试环境验证
#define SANDBOX     @"https://sandbox.itunes.apple.com/verifyReceipt"
//正式环境验证
#define AppStore    @"https://buy.itunes.apple.com/verifyReceipt"

@interface DiaryOCViewController () <UITableViewDelegate, UITableViewDataSource, DiarySectionOCTableViewCellDelegate, DiaryEditViewControllerDelegate,AddDiaryContentViewControllerDelegate, UIPickerViewDelegate, UIPickerViewDataSource,SKPaymentTransactionObserver,SKProductsRequestDelegate>
{
    AVPlayer *_audioPlayer;
    AVPlayerLayer *_playerLayer;
}
@property (strong, nonatomic) NSMutableDictionary *hisDic;
@property (nonatomic, strong) NSMutableArray *tableviewDatasArr;

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *emptyView;

@property (assign, nonatomic) NSInteger currentPart;

@property (assign, nonatomic) NSInteger currentSection;

@property (assign, nonatomic) NSInteger currentRow;

@property (strong, nonatomic) NSIndexPath *lastIndexPath;

@property (copy, nonatomic) NSString *lastDayStr;

@property (strong, nonatomic) NSMutableDictionary *heightDic;

@property (weak, nonatomic) UIButton *switchBtn;

@property (assign, nonatomic) CGFloat lastContentOffset;

@end

@implementation DiaryOCViewController

- (void)loadTwoYearsData {
    
    @weakify(self)
    
    if (self.tableView.contentOffset.y != 0) {
        [self.tableView setContentOffset:CGPointZero animated:YES];
    }
    
    
    dispatch_async(dispatch_get_main_queue(), ^{
        @strongify(self)
        
        NSString *yearStr = [NSString currentYear];
        
        self.lastIndexPath = nil;
        self.lastDayStr = nil;
        
        self.hisDic = [NSMutableDictionary dictionary];
        self.heightDic = [NSMutableDictionary dictionary];
        
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
        NSString *folderPath = [[[docPath stringByAppendingPathComponent:@"/"] stringByAppendingPathComponent:yearStr] stringByAppendingPathComponent:@"/"];
        NSError *error = nil;
        NSArray *fileNames = [fileManager contentsOfDirectoryAtPath:folderPath error:&error];
        for (NSString *fileName in fileNames) {
            NSString *searchFolderPath = [[docPath stringByAppendingPathComponent:@"/"] stringByAppendingPathComponent:yearStr];
            NSString *filePath = [searchFolderPath stringByAppendingPathComponent:fileName];
            if (![fileManager fileExistsAtPath:filePath]) { break; }
            
            NSDictionary *monthDic = [NSDictionary dictionaryWithContentsOfFile:filePath];
            NSString *fileName2 = [fileName substringToIndex:2];
            fileName2 = [NSString stringWithFormat:@"%ld.plist", fileName.integerValue + 12];
            
            // 整理一下数据
            NSMutableDictionary *tempDict = [NSMutableDictionary dictionaryWithDictionary:monthDic];
            NSArray *allKeys = monthDic.allKeys;
            for (int i = 0; i<allKeys.count; i++) {
                NSArray *arr = tempDict[allKeys[i]];
                if (arr.count == 0){
                    [tempDict removeObjectForKey: allKeys[i]];
                }
            }
            monthDic = tempDict;
            self.hisDic[fileName2] = monthDic;
        }
        
        
        yearStr = [NSString stringWithFormat:@"%ld", [NSString currentYear].integerValue - 1];
        
        docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
        folderPath = [[[docPath stringByAppendingPathComponent:@"/"] stringByAppendingPathComponent:yearStr] stringByAppendingPathComponent:@"/"];
        fileNames = [fileManager contentsOfDirectoryAtPath:folderPath error:&error];
        for (NSString *fileName in fileNames) {
            NSString *searchFolderPath = [[docPath stringByAppendingPathComponent:@"/"] stringByAppendingPathComponent:yearStr];
            NSString *filePath = [searchFolderPath stringByAppendingPathComponent:fileName];
            if (![fileManager fileExistsAtPath:filePath]) { break; }
            
            NSDictionary *monthDic = [NSDictionary dictionaryWithContentsOfFile:filePath];
            
            // 整理一下数据
            NSMutableDictionary *tempDict = [NSMutableDictionary dictionaryWithDictionary:monthDic];
            NSArray *allKeys = monthDic.allKeys;
            for (int i = 0; i<allKeys.count; i++) {
                NSArray *arr = tempDict[allKeys[i]];
                if (arr.count == 0){
                    [tempDict removeObjectForKey: allKeys[i]];
                }
            }
            monthDic = tempDict;
            self.hisDic[fileName] = monthDic;
        }
        
        
        NSArray *allMonthKeys = [self.hisDic.allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
            return [obj2 compare:obj1];
        }];
        
        [self.tableviewDatasArr removeAllObjects];
        for (int i = 0; i<allMonthKeys.count; i++) {
            
            NSDictionary *tempMonthDataDict = self.hisDic[allMonthKeys[i]];
            NSArray *allDayKeys = [tempMonthDataDict.allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                return [obj2 compare:obj1];
            }];
                 
            NSMutableArray *tempDayDatasArr = [NSMutableArray array];
            for (int j = 0; j<allDayKeys.count; j++) {

                [tempDayDatasArr addObject:@{@"dayStr":allDayKeys[j],
                                             @"dayDatas":tempMonthDataDict[allDayKeys[j]]
                                           }];
                
            }
                
            if (tempDayDatasArr.count > 0) {

                [self.tableviewDatasArr addObject:@{@"monthStr":allMonthKeys[i],
                                                      @"monthDatas":tempDayDatasArr
                }];
            }
            
        }
        
        if (self.hisDic.allKeys.count > 0) {
            
            BOOL isEmpty = YES;
            
            for (NSString *key in self.hisDic.allKeys) {
                if ([self.hisDic[key] isKindOfClass:[NSDictionary class]]) {
                    NSDictionary *valueDic = self.hisDic[key];
                    if (valueDic.allKeys.count > 0) {
                        isEmpty = NO;
                        break;
                    }
                }
            }
            
            if (isEmpty == YES) {
                self.tableView.hidden = YES;
                self.emptyView.hidden = NO;
            } else {
                self.tableView.hidden = NO;
                self.emptyView.hidden = YES;
            }
            
        } else {
            self.tableView.hidden = YES;
            self.emptyView.hidden = NO;
        }
        
        NSLog(@"self.hisDic === %@", self.hisDic);
        
        [self.tableView reloadData];
        
//        @weakify(self)
//        dispatch_async(dispatch_get_main_queue(), ^{
//            @strongify(self)
//            self.lastIndexPath = nil;
//            self.lastDayStr = nil;
//        });
    });
    
}

- (void)loadDataWithSelectYear:(NSString *)selectYear {
    
    @weakify(self)
    
    if (self.tableView.contentOffset.y != 0) {
        [self.tableView setContentOffset:CGPointZero animated:YES];
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        @strongify(self)
        
        NSString *yearStr = selectYear == nil ? [NSString currentYear] : selectYear;
        
        self.lastIndexPath = nil;
        self.lastDayStr = nil;
        
        self.hisDic = [NSMutableDictionary dictionary];
        
        self.heightDic = [NSMutableDictionary dictionary];
        
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
        NSString *folderPath = [[[docPath stringByAppendingPathComponent:@"/"] stringByAppendingPathComponent:yearStr] stringByAppendingPathComponent:@"/"];
        NSError *error = nil;
        if (![fileManager fileExistsAtPath:folderPath]) {
            self.tableView.hidden = YES;
            self.emptyView.hidden = NO;
            return;
        }
        NSArray *fileNames = [fileManager contentsOfDirectoryAtPath:folderPath error:&error];
        for (NSString *fileName in fileNames) {
            NSString *searchFolderPath = [[docPath stringByAppendingPathComponent:@"/"] stringByAppendingPathComponent:yearStr];
            NSString *filePath = [searchFolderPath stringByAppendingPathComponent:fileName];
            if (![fileManager fileExistsAtPath:filePath]) { break; }
            
            NSDictionary *monthDic = [NSDictionary dictionaryWithContentsOfFile:filePath];
            self.hisDic[fileName] = monthDic;
        }
        
        if (self.hisDic.allKeys.count > 0) {
            
            BOOL isEmpty = YES;
            
            for (NSString *key in self.hisDic.allKeys) {
                if ([self.hisDic[key] isKindOfClass:[NSDictionary class]]) {
                    NSDictionary *valueDic = self.hisDic[key];
                    if (valueDic.allKeys.count > 0) {
                        isEmpty = NO;
                        break;
                    }
                }
            }
            
            if (isEmpty == YES) {
                self.tableView.hidden = YES;
                self.emptyView.hidden = NO;
            } else {
                self.tableView.hidden = NO;
                self.emptyView.hidden = YES;
            }
            
        } else {
            self.tableView.hidden = YES;
            self.emptyView.hidden = NO;
        }
        
        NSLog(@"self.hisDic === %@", self.hisDic);
        
        [self.tableView reloadData];
        
//        @weakify(self)
//        dispatch_async(dispatch_get_main_queue(), ^{
//            @strongify(self)
//            self.lastIndexPath = nil;
//            self.lastDayStr = nil;
//        });
    });
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    [audioSession setActive:YES error:nil];
    
    [[NSNotificationCenter defaultCenter]
     addObserver:self selector:@selector(getMusic:) name:@"getMusic" object:nil];
    
    [[NSNotificationCenter defaultCenter]
     addObserver:self selector:@selector(stopMusic:) name:@"stopMusic" object:nil];
    
    [self setUserDefaultsStartState];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    UIView *footerBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 100.0)];
    DiaryOCFooterView *footerView = [[NSBundle mainBundle] loadNibNamed:@"DiaryOCFooterView" owner:self options:nil].lastObject;
    footerView.frame = footerBgView.bounds;
    [footerBgView addSubview:footerView];
    self.tableView.tableFooterView = footerBgView;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"DiarySectionOCTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"DiarySectionOCTableViewCell"];
    
    UIButton *switchBtn = [UIButton buttonWithType:0];
    switchBtn.frame = CGRectMake(0, 0, 200.0, 30.0);
    [switchBtn setTitle:[NSString currentYearAndMonth] forState:0];
    [switchBtn setTitleColor:[UIColor blackColor] forState:0];
    [switchBtn setImage:[UIImage imageNamed:@"向下"] forState:0];
    switchBtn.titleLabel.font = [UIFont systemFontOfSize:17.0 weight:UIFontWeightMedium];
    switchBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -30.0, 0, 0);
    switchBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 130.0, 0, 0);
    [switchBtn addTarget:self action:@selector(switchAction) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.titleView = switchBtn;
    self.switchBtn = switchBtn;
    
    @weakify(self)
    
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"createSucceed" object:nil] subscribeNext:^(id x) {
        @strongify(self)
        [self loadTwoYearsData];
    }];
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"editDiaryCompleted" object:nil] subscribeNext:^(id x) {
        @strongify(self)
        [self loadTwoYearsData];
    }];
    
}

//跳转到服务页面
-(void)getMusic:(NSNotification*)sender
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:_audioPlayer.currentItem];
    _audioPlayer= nil;
    
    AVPlayerItem *item = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://pdotools-resources.oss-cn-hangzhou.aliyuncs.com/bgmusic/%@.m4a",sender.object]]];
    _audioPlayer = [[AVPlayer alloc]initWithPlayerItem:item];
    [_audioPlayer play];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayDidEnd:)  name:AVPlayerItemDidPlayToEndTimeNotification object:_audioPlayer.currentItem];
}

//跳转到服务页面
-(void)stopMusic:(NSNotification*)sender
{
    [_audioPlayer pause];
}

- (void)moviePlayDidEnd:(NSNotification*)notification{

   AVPlayerItem * item = [notification object];

    [item seekToTime:kCMTimeZero];

    [_audioPlayer play];
}
// 重写父类成为响应者方法
- (BOOL)canBecomeFirstResponder {
    return YES;
}

- (void) remoteControlReceivedWithEvent: (UIEvent *) receivedEvent {
    if (receivedEvent.type == UIEventTypeRemoteControl) {

        switch (receivedEvent.subtype) { // 得到事件类型

            case UIEventSubtypeRemoteControlTogglePlayPause: // 暂停 ios6
                [_audioPlayer pause];// 调用你所在项目的暂停按钮的响应方法 下面的也是如此
                break;

            case UIEventSubtypeRemoteControlPreviousTrack:  // 上一首
                break;

            case UIEventSubtypeRemoteControlNextTrack: // 下一首
                break;

            case UIEventSubtypeRemoteControlPlay: //播放
                [_audioPlayer play];
                break;

            case UIEventSubtypeRemoteControlPause: // 暂停 ios7
                [_audioPlayer pause];
                break;

            default:
                break;
        }
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.tableView setContentOffset:CGPointZero animated:NO];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    @weakify(self)
    dispatch_async(dispatch_get_main_queue(), ^{
        @strongify(self)
//        NSString *yearStr = [self.switchBtn.currentTitle substringToIndex:4];
//        [self loadDataWithSelectYear:yearStr];
        [self loadTwoYearsData];
    });
    
    // 友盟页面统计
    [MobClick beginLogPageView:@"日记"];
    [MobClick event:@"pages_num" attributes:@{@"RiJi":@"进入日记"}];
}

// 友盟页面统计
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
    [MobClick endLogPageView:@"日记"];
    [MobClick event:@"pages_num" attributes:@{@"RiJi":@"离开日记"}];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
//    for (int i = 23; i >= 0; i --) {
//        CGFloat sectionHeight = [self.tableView rectForSection:i].origin.y;
//        if (scrollView.contentOffset.y >= sectionHeight) {
//            NSString *yearStr;
//
//            if (i < 12) {
//                yearStr = [NSString currentYear];
//            } else {
//                yearStr = [NSString stringWithFormat:@"%ld", [NSString currentYear].integerValue - 1];
//            }
//
//            if (i == 0 && [yearStr isEqualToString:[NSString currentYear]]) {
//
//            } else {
//                [self.switchBtn setTitle:[NSString stringWithFormat:@"%@-%02d", yearStr, 12 - (i / 12 == 1 ? i - 12 : i)] forState:0];
//            }
//            break;
//
//        }
//
//    }
    
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.lastContentOffset = scrollView.contentOffset.y;
}

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
//    if (self.lastContentOffset < scrollView.contentOffset.y) {
//        NSLog(@"向上滚动");
//    } else {
//        NSLog(@"向下滚动");
//    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 40;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
//    NSString *fileName = [NSString stringWithFormat:@"%02ld.plist", 24 - section];
    
    NSDictionary *sectionData = self.tableviewDatasArr[section];
    
    
    NSString *fileName = [NSString stringWithFormat:@"%02ld.plist", 24 - section];
    
//    NSArray *daysDatas = monthData[@"monthDatas"];
//    NSDictionary *daysDatas = monthDatas[indexPath.row];
////
//    NSString *fileName = monthData[@"monthStr"];
    NSArray *monthDatas = sectionData[@"monthDatas"];
    NSDictionary *daysData = monthDatas.firstObject;
    NSArray *diaryArr = daysData[@"dayDatas"];
    NSDictionary *diaryDict = diaryArr.firstObject;
    
    NSDictionary *dic = self.hisDic[fileName];
    
    
    NSArray *allKeys = [dic.allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2];
    }];
    allKeys = allKeys.reverseObjectEnumerator.allObjects;
    
    DiaryOCHeaderView *headView = [[NSBundle mainBundle] loadNibNamed:@"DiaryOCHeaderView" owner:self options:nil].lastObject;

    if (section < 12) {
        headView.label0.text = [NSString stringWithFormat:@"%@年 %ld月", [NSString currentYear], 12 - section];
    } else {
        headView.label0.text = [NSString stringWithFormat:@"%ld年 %ld月", [NSString currentYear].integerValue - 1, 24 - section];
    }
    NSString *timeStampStr = diaryDict[@"timeStampStr"];
    headView.label0.text = [NSString stringWithFormat:@"%@年 %@月",[NSString getYear:timeStampStr],[NSString getMonth:timeStampStr]];

    
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    DiaryOCSectionFooterView *footerView = [[NSBundle mainBundle] loadNibNamed:@"DiaryOCSectionFooterView" owner:self options:nil].lastObject;
    
    return footerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (self.heightDic[[NSString stringWithFormat:@"%ld_%ld", indexPath.section, indexPath.row]]) {
        return [self.heightDic[[NSString stringWithFormat:@"%ld_%ld", indexPath.section, indexPath.row]] floatValue];
    }
    
    
    NSDictionary *monthData = self.tableviewDatasArr[indexPath.section];
    
    NSArray *monthDatas = monthData[@"monthDatas"];
    NSDictionary *daysDatas = monthDatas[indexPath.row];
    NSArray *diarysArr = daysDatas[@"dayDatas"];
    
    NSString *dayStr = daysDatas[@"dayStr"];
    
//    NSString *dayStr = @"";
//    if (indexPath.row < allKeys.count) {
//        dayStr = allKeys[indexPath.row];
//    }

    CGFloat height = 35.0 + 90.0 + 10.0 * 2;
    
    if (self.lastIndexPath.section == indexPath.section) {
        if (self.lastDayStr.intValue > dayStr.intValue + 1) {
//            height += 30.0;
        }
    } else {
        self.lastIndexPath = indexPath;
    }
    
    if ([[self compareDayStringInIndexPath:indexPath] intValue]>0) {
        height += 30.0;
    }
    
    self.lastDayStr = dayStr;
    
//    NSArray *arr = dic[dayStr];
    
    [self.heightDic setValue:[NSString stringWithFormat:@"%f", height] forKey:[NSString stringWithFormat:@"%ld_%ld", indexPath.section, indexPath.row]];
    
    if (diarysArr.count == 0) { return 0; }
    
    for (NSDictionary *dic in diarysArr) {
        if ([dic[@"reasonDetailStr"] length] > 0) {
            
            NSString *reasonDetailStr = dic[@"reasonDetailStr"];
            if ([reasonDetailStr containsString:@"isAttributedString"]) {
                
                NSFileManager *fileManager = [NSFileManager defaultManager];
                NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
                NSString *folderPath = [docPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.txt",dic[@"timeStampStr"]]];
                
                if ([fileManager fileExistsAtPath:folderPath]) {
                
                    NSData *data = [fileManager contentsAtPath:folderPath];
                    NSAttributedString *attr = [NSKeyedUnarchiver unarchiveObjectWithData:data];
                    
                    //若列表需要显示图片，打开下列代码
                    __block NSMutableAttributedString *mutableAttr = [[NSMutableAttributedString alloc] initWithAttributedString:attr];

                    [attr enumerateAttributesInRange:NSMakeRange(0, attr.length) options:NSAttributedStringEnumerationReverse usingBlock:^(NSDictionary<NSAttributedStringKey,id> * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) {

                        NSTextAttachment *textAtt = attrs[@"NSAttachment"];

                        if (textAtt) {

//                            UIImage *tempImage = textAtt.image;
//
//                            CGFloat scale = tempImage.size.width / tempImage.size.height;
//                            CGFloat height = 80.0;
//                            CGFloat width = scale * height;
//                            if (scale > 1){
//                                width = 80;
//                                height = width/scale;
//                            }
//
//                            textAtt.bounds = CGRectMake(0, 0, width, height);
                            [mutableAttr replaceCharactersInRange:range withAttributedString:[[NSAttributedString alloc]initWithString:@""]];
                        }

                    }];
//
//                    height += [attr boundingRectWithSize:CGSizeMake(DEF_SCREEN_WIDTH - 75.0 - 22.0 - 30.0 * 2, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size.height+25;
                    
                    height += [[mutableAttr.string stringByTrimmingCharactersInSet:NSCharacterSet.newlineCharacterSet] boundingRectWithSize:CGSizeMake(DEF_SCREEN_WIDTH - 75.0 - 22.0 - 30.0 * 2, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15.0]} context:nil].size.height + 25.0;
                }else{
                    
                    height += [reasonDetailStr boundingRectWithSize:CGSizeMake(DEF_SCREEN_WIDTH - 75.0 - 22.0 - 30.0 * 2, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15.0]} context:nil].size.height + 25.0;
                }
                
            }else{
                
                height += [dic[@"reasonDetailStr"] boundingRectWithSize:CGSizeMake(DEF_SCREEN_WIDTH - 75.0 - 22.0 - 30.0 * 2, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15.0]} context:nil].size.height + 25.0;
            }
        }
    }
    height += (diarysArr.count - 1) * 90.0;
    
    if (@available(iOS 15.0, *)) {
        height += 20.0;
    }
    
    [self.heightDic setValue:[NSString stringWithFormat:@"%f", height] forKey:[NSString stringWithFormat:@"%ld_%ld", indexPath.section, indexPath.row]];
    
    return height;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//    return self.hisDic.allKeys.count;
    return self.tableviewDatasArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    NSDictionary *monthData = self.tableviewDatasArr[section];
    NSArray *daysDatas = monthData[@"monthDatas"];
    return daysDatas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    DiarySectionOCTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"DiarySectionOCTableViewCell"];
    if (cell == nil) {
        cell = [[DiarySectionOCTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"DiarySectionOCTableViewCell"];
    }
    
    cell.delegate = self;
    cell.currentPart = indexPath.section;
    cell.currentSection = indexPath.row;
    
    NSDictionary *monthData = self.tableviewDatasArr[indexPath.section];
    
    NSArray *monthDatas = monthData[@"monthDatas"];
    NSDictionary *daysDatas = monthDatas[indexPath.row];
    NSArray *diarysArr = daysDatas[@"dayDatas"];
    
    cell.compareDayStr = [self compareDayStringInIndexPath:indexPath];
    cell.dayArray = diarysArr;
    
    return cell;
}

-(NSString *)compareDayStringInIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary *monthData = self.tableviewDatasArr[indexPath.section];
    
    NSArray *monthDatas = monthData[@"monthDatas"];
    NSDictionary *daysDatas = monthDatas[indexPath.row];
    NSArray *diarysArr = daysDatas[@"dayDatas"];
    //处理间隔天数逻辑
    NSDictionary *tempDiaryDict = diarysArr.firstObject;
    NSString *timeStamp = tempDiaryDict[@"timeStampStr"];
    
    if ( indexPath.row == 0) {
        
        if (indexPath.section == 0) {
            //最新一条数据，跟今天作比较
            NSString *compareDayStr = [NSString compareDayDiffWithDate1:[NSString currentTimeStamp]  toDate2:timeStamp];
            
            return compareDayStr;
        }else{
            //每个月的最晚有日记的一天
            //上条数据
            NSDictionary *lastMonthData = self.tableviewDatasArr[indexPath.section-1];
            NSArray *lastMonthDatas = lastMonthData[@"monthDatas"];
            NSDictionary *lastDaysDatas = lastMonthDatas.lastObject;
            NSArray *lastDiarysArr = lastDaysDatas[@"dayDatas"];
            NSDictionary *lastTempDiaryDict = lastDiarysArr.firstObject;
            NSString *lastTimeStamp = lastTempDiaryDict[@"timeStampStr"];

            //比较
            NSString *compareDayStr = [NSString compareDayDiffWithDate1:timeStamp  toDate2:lastTimeStamp];
            
            return compareDayStr;
        }
        
    }else{
        //每个月非最后更新的日记
        //本条数据前面有记录的一天的数据
        NSDictionary *lastDaysDatas = monthDatas[indexPath.row-1];
        NSArray *lastDiarysArr = lastDaysDatas[@"dayDatas"];
        NSDictionary *lastTempDiaryDict = lastDiarysArr.firstObject;
        NSString *lastTimeStamp = lastTempDiaryDict[@"timeStampStr"];
        
        //比较
        NSString *compareDayStr = [NSString compareDayDiffWithDate1:timeStamp toDate2:lastTimeStamp];
        
        return compareDayStr;
    }
    return nil;
}

- (void)diarySectionOCTableViewCellSelectPart:(NSInteger)currentPart andSection:(NSInteger)currentSection andRow:(NSInteger)currentRow andDeletedDiaryStamp:(NSString *)timeStampStr {
    
    NSLog(@"currentPart === %ld", currentPart);
    NSLog(@"currentSection === %ld", currentSection);
    NSLog(@"currentRow === %ld", currentRow);
    
    _currentPart = currentPart;
    _currentSection = currentSection;
    _currentRow = currentRow;
    
    [self showEditAlert: timeStampStr];
}

-(void)diaryDeleteWithIndex:(NSInteger)index timeStamp:(NSString *)timeStamp{
    
    [self deleteRow:timeStamp];
}

-(void)attributeEditDoneWithDict:(NSDictionary *)dict attriStr:(NSAttributedString *)attriStr{
    
    [self diaryEditDoneWithDic:dict editIndex:0 attriStr:attriStr];
    
}

- (void)diaryEditDoneWithDic:(NSDictionary * _Nullable)dic editIndex: Int attriStr:(NSAttributedString * _Nullable)attriStr {
    
    NSLog(@"_currentPart === %ld", _currentPart);
    NSLog(@"_currentSection === %ld", _currentSection);
    NSLog(@"_currentRow === %ld", _currentRow);
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSString *folderPath = [[docPath stringByAppendingPathComponent:@"/"] stringByAppendingPathComponent:[NSString getYear:dic[@"timeStampStr"]]];
    NSString *fileName = [NSString stringWithFormat:@"%02ld.plist",[NSString getMonth:dic[@"timeStampStr"]].integerValue];
    
    NSString *monthSavePath = [folderPath stringByAppendingPathComponent:fileName];
    if (![fileManager fileExistsAtPath:folderPath]) {
        return;
    }
    
    NSDictionary *monthDatas = [NSDictionary dictionaryWithContentsOfFile:monthSavePath];
    NSMutableDictionary *hisDictionary = [NSMutableDictionary dictionaryWithDictionary:monthDatas];
    
    NSString *dayStr = [NSString getDay:dic[@"timeStampStr"]];
    NSMutableArray *dayArr = [NSMutableArray arrayWithArray:hisDictionary[dayStr]];
    for ( int i = 0;i<dayArr.count; i++) {
        
        NSDictionary *tempDict = dayArr[i];
        if ([dic[@"timeStampStr"] isEqualToString:tempDict[@"timeStampStr"]]) {
            
            [dayArr replaceObjectAtIndex:i withObject:dic];
            hisDictionary[dayStr] = dayArr.copy;
            [hisDictionary writeToFile:monthSavePath atomically:YES];
            break;
        }
        
    }
    
    //日记
    NSString *diaryFilePath = [NSString stringWithFormat:@"%@/diary.plist", docPath];
    NSMutableArray *diaryArr = [NSMutableArray arrayWithContentsOfFile:diaryFilePath];
    if (diaryArr == nil) {
        diaryArr = [NSMutableArray array];
    }
    for ( int i = 0;i<diaryArr.count; i++) {
        
        NSDictionary *tempDict = diaryArr[i];
        if ([dic[@"timeStampStr"] isEqualToString:tempDict[@"timeStampStr"]]) {
            
            [diaryArr replaceObjectAtIndex:i withObject:dic];
            [diaryArr writeToFile:diaryFilePath atomically:YES];
            break;
        }
    }
    
    //富文本储存
    NSString *attrDocPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    NSString *attrPath = [attrDocPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.txt",dic[@"timeStampStr"]]];
    NSData *attrData = [NSKeyedArchiver archivedDataWithRootObject:attriStr];
    [attrData writeToFile:attrPath atomically:YES];

    
    //心情
    NSDictionary *moodDic = @{@"mood": dic[@"moodStr"], @"timeStamp": dic[@"timeStampStr"]};
    NSString *moodFilePath = [NSString stringWithFormat:@"%@/mood.plist", docPath];
    NSMutableArray *moodArr = [NSMutableArray arrayWithContentsOfFile:moodFilePath];
    if (moodArr == nil) {
        moodArr = [NSMutableArray array];
    }
    for ( int i = 0;i<moodArr.count; i++) {
        
        NSDictionary *tempDict = moodArr[i];
        if ([dic[@"timeStampStr"] isEqualToString:tempDict[@"timeStamp"]]) {
            
            [moodArr replaceObjectAtIndex:i withObject:moodDic];
            [moodArr writeToFile:moodFilePath atomically:YES];
            break;
        }
    }
    
 
    //天气
    NSDictionary *weatherDic = @{@"weather": dic[@"weatherStr"], @"timeStamp": dic[@"timeStampStr"]};
    NSString *weatherFilePath = [NSString stringWithFormat:@"%@/weather.plist", docPath];
    NSMutableArray *weatherArr = [NSMutableArray arrayWithContentsOfFile:weatherFilePath];
    if (weatherArr == nil) {
        weatherArr = [NSMutableArray array];
    }
    for ( int i = 0;i<weatherArr.count; i++) {
        
        NSDictionary *tempDict = weatherArr[i];
        if ([dic[@"timeStampStr"] isEqualToString:tempDict[@"timeStamp"]]) {
            
            [weatherArr replaceObjectAtIndex:i withObject:weatherDic];
            [weatherArr writeToFile:weatherFilePath atomically:YES];
            break;
        }
    }

    //活动
    NSString *activityFilePath = [NSString stringWithFormat:@"%@/activity.plist", docPath];
    NSMutableArray *activityArr = [NSMutableArray arrayWithContentsOfFile:activityFilePath];
    if (activityArr == nil) {
        activityArr = [NSMutableArray array];
    }
    NSArray *editActivityArr = dic[@"reasonArray"];
    
    for ( int i = 0;i<activityArr.count; i++) {
        
        NSDictionary *tempDict = activityArr[i];
        if ([dic[@"timeStampStr"] isEqualToString:tempDict[@"timeStamp"]]) {
            
            [activityArr removeObjectAtIndex:i];
            i --;
        }
        
    }
    for ( int i = 0;i<editActivityArr.count; i++) {
        
        NSString *tempActivity = editActivityArr[i];
        NSDictionary *reasonDic = @{@"activity":tempActivity, @"timeStamp": dic[@"timeStampStr"]};
        
        [activityArr addObject:reasonDic];
    }
    [activityArr writeToFile:activityFilePath atomically:YES];
    

    [self loadTwoYearsData];
}

-(void)checkDetailDiaryWithData:(NSDictionary *)dict index:(NSInteger)editIndex{
    
    AddDiaryContentViewController *detailVC = [AddDiaryContentViewController new];
    detailVC.diaryDict = dict;
    detailVC.pageType = 2;
    detailVC.delegate = self;
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (void)showEditAlert:(NSString*)timeStampStr {
    
    PhotoStyleChooseView *photoStyleChooseView = [[PhotoStyleChooseView alloc] initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT) type:PageTypeEdit];
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:photoStyleChooseView];
    
    
    @weakify(self);
    photoStyleChooseView.albumBlock = ^{
        @strongify(self);
        [self jumpToEdit];
    };
    photoStyleChooseView.cameraBlock = ^{
        @strongify(self);
        [self deleteRowAlert: timeStampStr];
    };

//    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:@"请选择您要进行的操作" preferredStyle:UIAlertControllerStyleActionSheet];
//    [alertC addAction:[UIAlertAction actionWithTitle:@"编辑" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        [self jumpToEdit];
//    }]];
//    [alertC addAction:[UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        [self deleteRowAlert: timeStampStr];
//    }]];
//    [alertC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//    }]];
//    [self presentViewController:alertC animated:YES completion:nil];
}

- (void)jumpToEdit {
    
    NSDictionary *monthData = self.tableviewDatasArr[_currentPart];
    
    NSArray *monthDatas = monthData[@"monthDatas"];
    NSDictionary *daysDatas = monthDatas[_currentSection];
    NSArray *diarysArr = daysDatas[@"dayDatas"];
    NSDictionary *diaryDict = diarysArr[_currentRow];
    
    if (_currentRow > 0) {
        NSDictionary *firstDic = [NSDictionary dictionaryWithDictionary:diarysArr.firstObject];
        [diaryDict setValue:firstDic[@"weatherStr"] forKey:@"weatherStr"];
    }

    DiaryEditViewController *vc = [[DiaryEditViewController alloc] init];
    vc.dic = diaryDict;
    vc.delegate = self;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)deleteRowAlert:(NSString*)timeStampStr {
    
    [self.presentedViewController dismissViewControllerAnimated:YES completion:nil];
    
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定删除这条数据?" preferredStyle:UIAlertControllerStyleActionSheet];
    [alertC addAction:[UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self deleteRow: timeStampStr];
    }]];
    [alertC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertC animated:YES completion:nil];
}

- (void)deleteRow:(NSString*)timeStampStr {
    
    NSString *currentYear = NSString.currentYear;
    NSString *deletedYear = [NSString getYear:timeStampStr];
    NSString *deletedMonth = [NSString getMonth:timeStampStr];
    NSString *deletedDay = [NSString getDay:timeStampStr];
    NSString *fileName = [NSString stringWithFormat:@"%02ld.plist", deletedMonth.integerValue];
    
    NSString *hisDictKey;
    if (deletedYear == currentYear ) { // 删除今年
        hisDictKey = [NSString stringWithFormat:@"%02ld.plist", 12 + deletedMonth.integerValue];
    } else {
        hisDictKey = [NSString stringWithFormat:@"%02ld.plist", deletedMonth.integerValue];
    }
    
    NSMutableDictionary *monthDic = [NSMutableDictionary dictionaryWithDictionary:self.hisDic[hisDictKey]];
    
    NSString *dayStr = [NSString stringWithFormat:@"%02ld", deletedDay.integerValue];
    NSString *removeTimestampStr = @"";
    NSMutableArray *dayArr = [NSMutableArray arrayWithArray:monthDic[dayStr]];
    for (int i = 0; i < dayArr.count; i ++) {
        NSDictionary *dic = dayArr[i];
        if ([timeStampStr isEqualToString: dic[@"timeStampStr"]]) {
            [dayArr removeObjectAtIndex:i];
            removeTimestampStr = dic[@"timeStampStr"];
            break;
        }
    }
    
    if (dayArr.count == 0) {
        [monthDic removeObjectForKey: dayStr];
    } else {
        monthDic[dayStr] = dayArr;
    }

    NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSString *folderPath = [[docPath stringByAppendingPathComponent:@"/"] stringByAppendingPathComponent:deletedYear];
    NSString *filePath = [folderPath stringByAppendingPathComponent:fileName];
    [monthDic writeToFile:filePath atomically:YES];

    NSString *weatherPath = [docPath stringByAppendingPathComponent:@"/weather.plist"];
    NSMutableArray *weatherArr = [NSMutableArray arrayWithContentsOfFile:weatherPath];
    for (NSDictionary *dic in weatherArr.reverseObjectEnumerator) {
        if ([dic[@"timeStamp"] isEqualToString: removeTimestampStr]) {
            [weatherArr removeObject:dic];
        }
    }
    [weatherArr writeToFile:weatherPath atomically:YES];

    NSString *moodPath = [docPath stringByAppendingPathComponent:@"/mood.plist"];
    NSMutableArray *moodArr = [NSMutableArray arrayWithContentsOfFile:moodPath];
    for (NSDictionary *dic in moodArr.reverseObjectEnumerator) {
        if ([dic[@"timeStamp"] isEqualToString: removeTimestampStr]) {
            [moodArr removeObject:dic];
        }
    }
    [moodArr writeToFile:moodPath atomically:YES];

    NSString *activityPath = [docPath stringByAppendingPathComponent:@"/activity.plist"];
    NSMutableArray *activityArr = [NSMutableArray arrayWithContentsOfFile:activityPath];
    for (NSDictionary *dic in activityArr.reverseObjectEnumerator) {
        if ([dic[@"timeStamp"] isEqualToString: removeTimestampStr]) {
            [activityArr removeObject:dic];
        }
    }
    [activityArr writeToFile:activityPath atomically:YES];

//    [self loadDataWithSelectYear:yearStr];
    [self loadTwoYearsData];
}

- (void)switchAction {
    UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(35.0, 70.0, 200.0, 240.0)];
    pickerView.delegate = self;
    pickerView.dataSource = self;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        NSString *yearStr = [self.switchBtn.currentTitle substringToIndex:4];
        NSString *monthStr = [self.switchBtn.currentTitle substringFromIndex:5];
        
        [pickerView selectRow:[yearStr isEqualToString:[NSString currentYear]] ? 0 : 1 inComponent:0 animated:NO];
        [pickerView selectRow:monthStr.intValue - 1 inComponent:1 animated:NO];
    });
    
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:@"请选择时间\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" preferredStyle:UIAlertControllerStyleAlert];
    [alertC.view addSubview:pickerView];
    [alertC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        NSInteger selectIndex0 = [pickerView selectedRowInComponent:0];
        NSInteger selectIndex1 = [pickerView selectedRowInComponent:1];
        
        
        if (selectIndex0 == 0 && selectIndex1 + 1 > [NSString currentMonth].integerValue) {
            [SVProgressHUD showErrorWithStatus:@"不能选择今天之后的日期"];
            [SVProgressHUD dismissWithDelay:2.0];
            return;
        }
        
        NSString *selectYear = selectIndex0 == 0 ? [NSString currentYear] : [NSString stringWithFormat:@"%ld", [NSString currentYear].integerValue - 1];
        NSString *selectMonth = [NSString stringWithFormat:@"%02ld", selectIndex1 + 1];

        [self.switchBtn setTitle:[NSString stringWithFormat:@"%@-%@", selectYear, selectMonth] forState:0];
        
        for (int i = 0; i<self.tableviewDatasArr.count; i++) {
            
            
            NSDictionary *monthDatasDict = self.tableviewDatasArr[i];
            NSArray *monthDatas = monthDatasDict[@"monthDatas"];
            NSDictionary *daysData = monthDatas.firstObject;
            NSArray *diaryArr = daysData[@"dayDatas"];
            NSDictionary *diaryDict = diaryArr.firstObject;
            NSString *timeStampStr = diaryDict[@"timeStampStr"];
            NSString *tempStr = [NSString stringWithFormat:@"%@-%@",[NSString getYear:timeStampStr],[NSString getMonth:timeStampStr]];
            
            if ([tempStr isEqualToString:[NSString stringWithFormat:@"%@-%@", selectYear, selectMonth]]) {
                
                [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:i] atScrollPosition:UITableViewScrollPositionTop animated:YES];
                break;
            }
            
            if (i == self.tableviewDatasArr.count - 1) {
                
                [SVProgressHUD showErrorWithStatus:@"该月份没有日记"];
                [SVProgressHUD dismissWithDelay:1.0];
            }
            
        }
        

        
//        NSInteger month = 0;
//
//        if (selectIndex0 == 0) {
//            month = 12 - selectIndex1;
//        } else if (selectIndex0 == 1) {
//            month = 24 - selectIndex1;
//        }
//
////        [NSString stringWithFormat:@"%@年 %ld月", [NSString currentYear], 12 - section];
//
//        for (int i = 24; i > 0; i --) {
//
//            CGFloat sectionHeight = [self.tableView rectForSection:i - 1].origin.y;
//
//            NSLog(@"month === %ld", month);
//            NSLog(@"i === %d", i);
//
//            if (month == i) {
//                NSLog(@"sectionHeight === %f", sectionHeight);
//                NSLog(@"self.tableView.contentSize.height === %f", self.tableView.contentSize.height);
//
//                if (sectionHeight > self.tableView.contentSize.height - self.tableView.height) {
//                    [self.tableView setContentOffset:CGPointMake(0, self.tableView.contentSize.height - self.tableView.height + 100.0) animated:YES];
//                } else {
//                    [self.tableView setContentOffset:CGPointMake(0, sectionHeight) animated:YES];
//                }
//
//                break;
//            }
//        }
//
    }]];
    [alertC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                
    }]];
    [self presentViewController:alertC animated:YES completion:nil];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    
    
    
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (component == 0) {
        return 2;
    }
    return 12;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    
    if (component == 0) {
        if (row == 0) {
            return [NSString currentYear];
        }
        return [NSString stringWithFormat:@"%ld", [NSString currentYear].integerValue - 1];
    }
    return [NSString stringWithFormat:@"%02ld月", row + 1];
}


-(NSMutableArray *)tableviewDatasArr{
    if (!_tableviewDatasArr) {
        _tableviewDatasArr = [NSMutableArray array];
        
    }
    return _tableviewDatasArr;
}

- (void)setUserDefaultsStartState
{
    //第一次运行创建
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"group.com.moodDiary.StartState"] == nil)
    {
        [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:@"group.com.moodDiary.StartState"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    else
    {
        SKReceiptRefreshRequest *request = [[SKReceiptRefreshRequest alloc] init];
        request.delegate = self;
        [request start];
//        [self verifyPurchaseWithPaymentTransaction:nil];
    }
}

//获取请求完成和失败的结果
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
    NSLog(@"------------------错误-----------------:%@", error);
}
- (void)requestDidFinish:(SKRequest *)request{
    NSLog(@"------------反馈信息结束-----------------");
    [self verifyPurchaseWithPaymentTransaction:nil];
}

/**
 *  验证购买，避免越狱软件模拟苹果请求达到非法购买问题
 票据的校验是保证内购安全完成的非常关键的一步，一般有三种方式：
 1、服务器验证，获取票据信息后上传至信任的服务器，由服务器完成与App Store的验证（提倡使用此方法，比较安全）
 2、本地票据校验
 3、本地App Store请求验证
 *
 */
-(void)verifyPurchaseWithPaymentTransaction:(SKPaymentTransaction *)transaction{
    ///解除监听
    //[[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
    
    //从沙盒中获取交易凭证并且拼接成请求体数据
    NSURL *receiptUrl=[[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receiptData=[NSData dataWithContentsOfURL:receiptUrl];
    if (!receiptData) {
        if([[NSUserDefaults standardUserDefaults] objectForKey:@"codeString"] != nil){
            [[NSNotificationCenter defaultCenter]
             addObserver:self selector:@selector(passView:) name:@"passView" object:nil];
            return  ;
        }else{
            PayViewController *loginController = [[PayViewController alloc]init];
            loginController.modalPresentationStyle = UIModalPresentationFullScreen;
            [self presentViewController:loginController animated:YES completion:^{
            }];
            return  ;
        }
    }
    NSString *receiptString=[receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];//转化为base64字符串
    NSLog(@"内购完成的收据为：%@",receiptString);
    [self saveReceiptData:@{@"receipt":receiptString,
                            @"userID":@"123456789"}];
    [self appVerificationReceipt:receiptString];
    

}

-(void)passView:(NSNotification*)sender
{
    PayViewController *loginController = [[PayViewController alloc]init];
    //新建导航控制器，解决model页面无法使用push
    loginController.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:loginController animated:YES completion:^{
    }];
}
///APP直接去苹果服务器验证
- (void)appVerificationReceipt:(NSString *)receiptString {
    NSString *bodyString = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\", \"password\" : \"%@\"}", receiptString,@"8aa12c81702b4ddd8668753de2fb2403"];//拼接请求数据
//    NSString *bodyString = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\"}", receiptString];//拼接请求数据
    NSData *bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *url = [NSURL URLWithString:AppStore];
    NSMutableURLRequest *requestM = [NSMutableURLRequest requestWithURL:url];
    requestM.HTTPBody = bodyData;
    requestM.HTTPMethod = @"POST";
    
    // 创建连接并发送同步请求
    NSError *error = nil;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:requestM returningResponse:nil error:&error];
    if (error) {
        NSLog(@"验证购买过程中发生错误，错误信息：%@",error.localizedDescription);
        return;
    }
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:nil];
    NSLog(@"++++++++++++%@",dic);
    if ([dic[@"status"] intValue]==0) {
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
        NSDate *date = [dateFormatter dateFromString:[[dic[@"latest_receipt_info"][0] objectForKey:@"expires_date"] substringToIndex:19]];
        
        NSTimeInterval hour = 60 * 60 * 8;
        // 一小时后
        NSDate *h1 = [date dateByAddingTimeInterval:hour];
        
        NSString *dateTime=[dateFormatter stringFromDate:[NSDate date]];
        NSDate *dateNow = [dateFormatter dateFromString:dateTime];
        
        if(h1 != nil){
            NSComparisonResult result = [dateNow compare:h1];
                if (result == NSOrderedDescending) {
                    //在指定时间前面 过了指定时间 过期
                    NSLog(@"oneDay  is in the future");
                    [[NSUserDefaults standardUserDefaults] setValue:0 forKey:@"payStatus"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    
                    if([[NSUserDefaults standardUserDefaults] objectForKey:@"codeString"] != nil){
                        [[NSNotificationCenter defaultCenter]
                         addObserver:self selector:@selector(passView:) name:@"passView" object:nil];
                    }else{
                        PayViewController *loginController = [[PayViewController alloc]init];
                        loginController.modalPresentationStyle = UIModalPresentationFullScreen;
                        [self presentViewController:loginController animated:YES completion:^{
                        }];
                    }
                }
        }else{
            [[NSUserDefaults standardUserDefaults] setValue:0 forKey:@"payStatus"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            if([[NSUserDefaults standardUserDefaults] objectForKey:@"codeString"] != nil){
                [[NSNotificationCenter defaultCenter]
                 addObserver:self selector:@selector(passView:) name:@"passView" object:nil];
            }else{
                PayViewController *loginController = [[PayViewController alloc]init];
                loginController.modalPresentationStyle = UIModalPresentationFullScreen;
                [self presentViewController:loginController animated:YES completion:^{
                }];
            }
        }
        
        NSLog(@"++++----%@---%@",h1,dateNow);

        ///解除监听
        [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
        [self removeLocReceiptData];
    } else if([dic[@"status"] intValue]==21006){

        [[NSUserDefaults standardUserDefaults] setValue:0 forKey:@"payStatus"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        if([[NSUserDefaults standardUserDefaults] objectForKey:@"codeString"] != nil){
            [[NSNotificationCenter defaultCenter]
             addObserver:self selector:@selector(passView:) name:@"passView" object:nil];
        }else{
            PayViewController *loginController = [[PayViewController alloc]init];
            loginController.modalPresentationStyle = UIModalPresentationFullScreen;
            [self presentViewController:loginController animated:YES completion:^{
            }];
        }
    }
}

#pragma mark -- 本地保存一次支付凭证
static NSString *const kSaveReceiptData = @"kSaveReceiptData";

- (void)saveReceiptData:(NSDictionary *)receiptData
{
    [[NSUserDefaults standardUserDefaults] setValue:receiptData forKey:kSaveReceiptData];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (NSDictionary *)getReceiptData
{
    return [[NSUserDefaults standardUserDefaults] valueForKey:kSaveReceiptData];
}

- (void)removeLocReceiptData
{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kSaveReceiptData];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

@end
